package com.zhuhjay.common.servlet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.util.*;

/**
 * Request的包装对象, 使得开放一些限制的功能
 * @author ZhuHJay
 * @date 2022/3/21 21:10
 */
public class RequestWrapper extends HttpServletRequestWrapper {
    private final Map<String,String[]> params;

    public RequestWrapper(HttpServletRequest request) throws IOException{
        super(request);
        this.params = new HashMap<>(request.getParameterMap());
    }

    public void addParameters(Map<String,Object> extraParams){
        Set<String> strings = extraParams.keySet();
        for (String string : strings) {
            Object object = extraParams.get(string);
            addParameters(string,object);
        }
    }

    @Override
    public String getParameter(String name){
        String[] values = params.get(name);
        if(values == null || values.length == 0){
            return null;
        }
        return values[0];
    }

    @Override
    public Map<String,String[]> getParameterMap(){
        return params;
    }

    @Override
    public String[] getParameterValues(String name){
        return params.get(name);
    }

    @Override
    public Enumeration<String> getParameterNames(){
        Vector<String> nameList = new Vector<>();
        for(Map.Entry<String,String[]> entry: params.entrySet()){
            nameList.add(entry.getKey());
        }
        return nameList.elements();
    }
    public void addParameters(String name,Object value){
        if(null != value){
            if(value instanceof String[]){
                params.put(name,(String[]) value);
            }else if(value instanceof String){
                params.put(name,new String[]{((String) value)});
            }else{
                params.put(name,new String[]{String.valueOf(value)});
            }
        }
    }
}
